// 圣经问答游戏 - 本地存储管理

class GameStorage {
    constructor() {
        this.storageKey = 'bibleQuizGame';
        this.defaultData = {
            userStats: {
                totalQuestions: 0,
                totalCorrect: 0,
                totalBadges: 0,
                gamesPlayed: 0,
                bestScore: 0,
                longestStreak: 0,
                playDays: [],
                lastPlayDate: null
            },
            achievements: {},
            settings: {
                soundEnabled: true,
                volume: 50,
                largeFont: false,
                darkMode: false
            },
            gameHistory: []
        };
        
        this.initializeStorage();
    }

    // 初始化存储
    initializeStorage() {
        const existingData = this.loadData();
        if (!existingData) {
            this.saveData(this.defaultData);
        }
    }

    // 加载数据
    loadData() {
        try {
            const data = localStorage.getItem(this.storageKey);
            return data ? JSON.parse(data) : null;
        } catch (error) {
            console.error('加载数据失败:', error);
            return null;
        }
    }

    // 保存数据
    saveData(data) {
        try {
            localStorage.setItem(this.storageKey, JSON.stringify(data));
            return true;
        } catch (error) {
            console.error('保存数据失败:', error);
            return false;
        }
    }

    // 获取用户统计
    getUserStats() {
        const data = this.loadData();
        return data ? data.userStats : this.defaultData.userStats;
    }

    // 更新用户统计
    updateUserStats(updates) {
        const data = this.loadData() || this.defaultData;
        data.userStats = { ...data.userStats, ...updates };
        
        // 更新游戏天数
        const today = new Date().toDateString();
        if (!data.userStats.playDays.includes(today)) {
            data.userStats.playDays.push(today);
        }
        data.userStats.lastPlayDate = today;
        
        this.saveData(data);
        return data.userStats;
    }

    // 记录游戏结果
    recordGameResult(gameResult) {
        const data = this.loadData() || this.defaultData;
        
        // 更新统计
        const stats = data.userStats;
        stats.totalQuestions += gameResult.totalQuestions;
        stats.totalCorrect += gameResult.correctAnswers;
        stats.gamesPlayed += 1;
        
        if (gameResult.score > stats.bestScore) {
            stats.bestScore = gameResult.score;
        }
        
        if (gameResult.maxStreak > stats.longestStreak) {
            stats.longestStreak = gameResult.maxStreak;
        }
        
        // 添加到游戏历史
        const historyEntry = {
            date: new Date().toISOString(),
            difficulty: gameResult.difficulty,
            score: gameResult.score,
            accuracy: gameResult.accuracy,
            maxStreak: gameResult.maxStreak,
            timeTaken: gameResult.timeTaken
        };
        
        data.gameHistory.unshift(historyEntry);
        
        // 只保留最近50场游戏记录
        if (data.gameHistory.length > 50) {
            data.gameHistory = data.gameHistory.slice(0, 50);
        }
        
        this.saveData(data);
        return stats;
    }

    // 获取成就状态
    getAchievements() {
        const data = this.loadData();
        return data ? data.achievements : {};
    }

    // 解锁成就
    unlockAchievement(achievementId) {
        const data = this.loadData() || this.defaultData;
        
        if (!data.achievements[achievementId]) {
            data.achievements[achievementId] = {
                unlocked: true,
                unlockedDate: new Date().toISOString()
            };
            
            // 更新徽章总数
            data.userStats.totalBadges = Object.keys(data.achievements).length;
            
            this.saveData(data);
            return true; // 新解锁
        }
        
        return false; // 已经解锁
    }

    // 检查成就是否已解锁
    isAchievementUnlocked(achievementId) {
        const achievements = this.getAchievements();
        return achievements[achievementId] && achievements[achievementId].unlocked;
    }

    // 获取设置
    getSettings() {
        const data = this.loadData();
        return data ? data.settings : this.defaultData.settings;
    }

    // 更新设置
    updateSettings(updates) {
        const data = this.loadData() || this.defaultData;
        data.settings = { ...data.settings, ...updates };
        this.saveData(data);
        return data.settings;
    }

    // 获取游戏历史
    getGameHistory(limit = 10) {
        const data = this.loadData();
        const history = data ? data.gameHistory : [];
        return limit ? history.slice(0, limit) : history;
    }

    // 获取统计摘要
    getStatsSummary() {
        const stats = this.getUserStats();
        const achievements = this.getAchievements();
        const history = this.getGameHistory(5);
        
        return {
            totalQuestions: stats.totalQuestions,
            totalCorrect: stats.totalCorrect,
            accuracy: stats.totalQuestions > 0 ? 
                Math.round((stats.totalCorrect / stats.totalQuestions) * 100) : 0,
            gamesPlayed: stats.gamesPlayed,
            bestScore: stats.bestScore,
            longestStreak: stats.longestStreak,
            totalBadges: Object.keys(achievements).length,
            playDays: stats.playDays.length,
            recentGames: history
        };
    }

    // 导出数据
    exportData() {
        const data = this.loadData();
        if (data) {
            const exportData = {
                ...data,
                exportDate: new Date().toISOString(),
                version: '1.0'
            };
            return JSON.stringify(exportData, null, 2);
        }
        return null;
    }

    // 导入数据
    importData(jsonString) {
        try {
            const importData = JSON.parse(jsonString);
            
            // 验证数据结构
            if (importData.userStats && importData.achievements && importData.settings) {
                // 合并数据而不是完全替换
                const currentData = this.loadData() || this.defaultData;
                
                // 合并统计数据（取较大值）
                const mergedStats = {
                    totalQuestions: Math.max(currentData.userStats.totalQuestions, importData.userStats.totalQuestions || 0),
                    totalCorrect: Math.max(currentData.userStats.totalCorrect, importData.userStats.totalCorrect || 0),
                    gamesPlayed: Math.max(currentData.userStats.gamesPlayed, importData.userStats.gamesPlayed || 0),
                    bestScore: Math.max(currentData.userStats.bestScore, importData.userStats.bestScore || 0),
                    longestStreak: Math.max(currentData.userStats.longestStreak, importData.userStats.longestStreak || 0),
                    playDays: [...new Set([...currentData.userStats.playDays, ...(importData.userStats.playDays || [])])],
                    lastPlayDate: importData.userStats.lastPlayDate || currentData.userStats.lastPlayDate
                };

                // 合并成就
                const mergedAchievements = {
                    ...currentData.achievements,
                    ...importData.achievements
                };

                // 合并游戏历史
                const mergedHistory = [
                    ...(importData.gameHistory || []),
                    ...currentData.gameHistory
                ].slice(0, 50); // 只保留最近50场

                const mergedData = {
                    userStats: mergedStats,
                    achievements: mergedAchievements,
                    settings: { ...currentData.settings, ...importData.settings },
                    gameHistory: mergedHistory
                };

                mergedData.userStats.totalBadges = Object.keys(mergedAchievements).length;

                this.saveData(mergedData);
                return true;
            }
            return false;
        } catch (error) {
            console.error('导入数据失败:', error);
            return false;
        }
    }

    // 重置所有数据
    resetAllData() {
        try {
            localStorage.removeItem(this.storageKey);
            this.initializeStorage();
            return true;
        } catch (error) {
            console.error('重置数据失败:', error);
            return false;
        }
    }

    // 清理过期数据
    cleanupOldData() {
        const data = this.loadData();
        if (!data) return;

        // 清理超过30天的游戏记录
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

        data.gameHistory = data.gameHistory.filter(game => 
            new Date(game.date) > thirtyDaysAgo
        );

        // 清理超过90天的游戏天数记录
        const ninetyDaysAgo = new Date();
        ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);

        data.userStats.playDays = data.userStats.playDays.filter(day => 
            new Date(day) > ninetyDaysAgo
        );

        this.saveData(data);
    }

    // 获取存储使用情况
    getStorageInfo() {
        try {
            const data = this.exportData();
            const sizeInBytes = new Blob([data]).size;
            const sizeInKB = Math.round(sizeInBytes / 1024 * 100) / 100;
            
            return {
                size: sizeInKB,
                unit: 'KB',
                lastModified: new Date().toISOString()
            };
        } catch (error) {
            return { size: 0, unit: 'KB', error: error.message };
        }
    }
}

// 创建全局存储实例
window.gameStorage = new GameStorage();